package com.yicong.ants.scenic

import android.app.AlertDialog
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ClipboardUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.cchao.simplelib.core.UiHelper
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity
import com.cchao.simplelib.util.StringHelper
import com.cchao.simplelib.util.UrlUtil
import com.yicong.ants.Constants
import com.yicong.ants.R
import com.yicong.ants.databinding.PayOrderDialogBinding
import com.yicong.ants.databinding.ScenicOrderDetailFragmentBinding
import com.yicong.ants.databinding.TicketDialogBinding
import com.yicong.ants.manager.UserManager
import com.yicong.ants.manager.config.ZzConfigs
import com.yicong.ants.scenic.viewModel.ScenicViewModel
import java.util.Date
import java.util.Timer
import java.util.TimerTask

class ScenicOrderDetailFragment : Fragment() {
    private lateinit var binding: ScenicOrderDetailFragmentBinding
    private val scenicViewModel: ScenicViewModel by activityViewModels()
    private val args: ScenicOrderDetailFragmentArgs by navArgs()
    private var timer: Timer? = null
    private var remainingPayTime: Long = 0
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        BarUtils.setStatusBarLightMode(requireActivity(), false);
        binding = ScenicOrderDetailFragmentBinding.inflate(layoutInflater, container, false)
        binding.backBtn.setOnClickListener { findNavController().navigateUp() }
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.serviceBtn.setOnClickListener {
            if (UserManager.notLogin()) {
                UiHelper.showToast("请先登录账号")
                return@setOnClickListener
            }
            val map: MutableMap<String, String> = HashMap()
            map["c1"] = UserManager.getMobile()
            map["c2"] = UserManager.getUserId()
            map["c3"] = "android"
            val userBean = UserManager.getUserBean()
            if (StringHelper.isNotEmpty(userBean.id_card_name)) {
                map["c4"] = userBean.id_card_name
                map["c5"] = "星级：" + userBean.level + " 活跃度：" + userBean.energy
            }
            val endUrl = UrlUtil.buildUrl(Constants.Customer_Chat, map)
            ZzConfigs.toWebActivityCheckLogin(requireContext(), "客服中心", endUrl)
        }
        scenicViewModel.ticketOrder.observe(viewLifecycleOwner) { it ->
            it?.bindProgressBar(binding.progressBar)
                ?.onComplete {
                    val data = it.data
                    binding.data = data
                    binding.orderNumberLl.setOnClickListener {
                        ClipboardUtils.copyText(data?.customerOrderNo)
                        ToastUtils.showLong("订单号已复制到剪切板")
                    }
                    binding.createTimeLl.visibility = View.GONE
                    binding.travelDateLl.visibility = View.VISIBLE
                    binding.buyerInfoLl.visibility = View.VISIBLE

                    binding.openTimeBtn.visibility = View.GONE
                    binding.buyDesBtn.visibility = View.GONE
                    binding.refundDesBtn.visibility = View.GONE

                    binding.lName.visibility = View.GONE
                    binding.lType.text = "项目名称"
                    binding.lAddress.visibility = View.GONE

                    when (data?.orderStatus) {
                        //待支付 = 1 ,出票中 = 2,已出票 = 3 ,出票失败 = 4 ,退订中 = 5 ,退订失败 = 6 ,已退订 = 7 , 已取消 = 99
                        "1" -> {
                            binding.stateIv.setImageResource(R.mipmap.scenic_state_wait)
                            binding.btnsLl.visibility = View.VISIBLE
                            remainingPayTime = data.remainingPayTime
                            startTimer()
                            binding.createTimeLl.visibility = View.VISIBLE
                            binding.travelDateLl.visibility = View.GONE
                            binding.buyerInfoLl.visibility = View.GONE

                            binding.openTimeBtn.visibility = View.VISIBLE
                            binding.buyDesBtn.visibility = View.VISIBLE
                            binding.refundDesBtn.visibility = View.VISIBLE

                            binding.lName.visibility = View.VISIBLE
                            binding.lType.text = "门票类型"
                            binding.lAddress.visibility = View.VISIBLE
                        }

                        "2" -> {
                            binding.stateIv.setImageResource(R.mipmap.scenic_state_wait)
                        }

                        "3" -> binding.stateIv.setImageResource(R.mipmap.ic_ticket_order_success)
                        "5" -> binding.stateIv.setImageResource(R.mipmap.scenic_state_ing)
                        "4", "6" -> binding.stateIv.setImageResource(R.mipmap.scenic_state_fail)
                        "7", "99" -> binding.stateIv.setImageResource(R.mipmap.scenic_state_cancel)
                    }
                    binding.cancelBtn.setOnClickListener {
                        AlertDialog.Builder(context).setTitle("温馨提示")
                            .setMessage("是否取消订单？").setNegativeButton("否", null)
                            .setPositiveButton("是") { _, _ ->
                                scenicViewModel.cancelOrder(
                                    requireActivity() as BaseTitleBarActivity<*>,
                                    data?.customerOrderNo ?: ""
                                )
                                scenicViewModel.cancelResult.observe(viewLifecycleOwner) {
                                    it?.bindProgressBar(binding.progressBar)
                                        ?.onComplete {
                                            scenicViewModel.getOrderDetail(
                                                requireActivity() as BaseTitleBarActivity<*>,
                                                args.id
                                            )
                                            remainingPayTime = 0
                                            binding.payTimeTv.text = ""
                                            binding.btnsLl.visibility = View.GONE
                                        }
                                }
                            }.show()
                        AlertDialog.Builder(requireActivity())
                    }
                    binding.openTimeBtn.setOnClickListener {
                        val dialogBinding = TicketDialogBinding.inflate(layoutInflater)
                        AlertDialog.Builder(requireActivity()).setView(dialogBinding.root)
                            .show().apply {
                                window?.setBackgroundDrawable(null)
                                dialogBinding.okBtn.setOnClickListener {
                                    dismiss()
                                }
                                dialogBinding.closeBtn.setOnClickListener {
                                    dismiss()
                                }
                                dialogBinding.titleTv.text = "开放时间"
                                dialogBinding.messageTv.text = data?.openTime
                            }
                    }
                    binding.buyDesBtn.setOnClickListener {
                        val dialogBinding = TicketDialogBinding.inflate(layoutInflater)
                        AlertDialog.Builder(requireActivity()).setView(dialogBinding.root)
                            .show().apply {
                                window?.setBackgroundDrawable(null)
                                dialogBinding.okBtn.setOnClickListener {
                                    dismiss()
                                }
                                dialogBinding.closeBtn.setOnClickListener {
                                    dismiss()
                                }
                                dialogBinding.titleTv.text = "购票说明"
                                dialogBinding.messageTv.text = data?.bookNotice
                            }
                    }
                    binding.refundDesBtn.setOnClickListener {
                        val dialogBinding = TicketDialogBinding.inflate(layoutInflater)
                        AlertDialog.Builder(requireActivity()).setView(dialogBinding.root)
                            .show().apply {
                                window?.setBackgroundDrawable(null)
                                dialogBinding.okBtn.setOnClickListener {
                                    dismiss()
                                }
                                dialogBinding.closeBtn.setOnClickListener {
                                    dismiss()
                                }
                                dialogBinding.titleTv.text = "退改说明"
                                dialogBinding.messageTv.text = data?.refundChangeRule
                            }
                    }
                    binding.payBtn.setOnClickListener {
                        val dialogBinding = PayOrderDialogBinding.inflate(layoutInflater)
                        AlertDialog.Builder(requireActivity()).setView(dialogBinding.root)
                            .setOnDismissListener {
                                KeyboardUtils.hideSoftInput(requireActivity())
                            }
                            .show().apply {
                                window?.setBackgroundDrawable(null)
                                dialogBinding.closeBtn.setOnClickListener {
                                    dismiss()
                                }
                                dialogBinding.ybtTv.text = "${data?.coin}ybt"
                                dialogBinding.passwordEt.setOnCompleteListener { password ->
                                    scenicViewModel.payOrder(
                                        requireActivity() as BaseTitleBarActivity<*>,
                                        data?.customerOrderNo ?: "",
                                        password
                                    )
                                    scenicViewModel.payResult.observe(viewLifecycleOwner) {
                                        it?.bindProgressBar(binding.progressBar)
                                            ?.onComplete(false) {
                                                dismiss()
                                                scenicViewModel.getOrderDetail(
                                                    requireActivity() as BaseTitleBarActivity<*>,
                                                    args.id
                                                )
                                                remainingPayTime = 0
                                                binding.payTimeTv.text = ""
                                                binding.btnsLl.visibility = View.GONE
                                            }
                                    }
                                }
                                dialogBinding.passwordEt.focus()
                                dialogBinding.passwordEt.postDelayed({
                                    KeyboardUtils.showSoftInput(
                                        requireActivity()
                                    )
                                }, 100)
                            }
                    }
                }?.onError {
                    findNavController().navigateUp()
                }
        }
        scenicViewModel.getOrderDetail(requireActivity() as BaseTitleBarActivity<*>, args.id)
    }

    private fun startTimer() {
        timer?.cancel()
        if (remainingPayTime < 0) return
        timer = Timer()
        timer?.scheduleAtFixedRate(object : TimerTask() {
            override fun run() {
                remainingPayTime--
                if (remainingPayTime < 0) {
                    timer?.cancel()
                    Handler(Looper.getMainLooper()).post {
                        scenicViewModel.getScenicDetail(
                            args.id,
                            requireActivity() as BaseTitleBarActivity<*>
                        )
                    }
                    binding.payTimeTv.post {
                        binding.payTimeTv.text = ""
                    }
                    return
                }
                binding.payTimeTv.post {
                    binding.payTimeTv.text =
                        "支付剩余时间${
                            TimeUtils.date2String(
                                Date(remainingPayTime * 1000),
                                "mm:ss"
                            )
                        }"
                }
            }
        }, 0, 1000)
    }

    override fun onDestroy() {
        super.onDestroy()
        timer?.cancel()
    }
}